<?php
/**
 * Author Yulin
 * Email  dwzhanglong@126.com
 * Date   2016-6-22
 * Func   登录
 */
defined('IN_YuLin') || exit('NO PERMIT!');

!$_SESSION['agent_login_fail'] && $_SESSION['agent_login_fail'] = 0;
($_SESSION['agent_login_fail'] > 10) && exit(json_encode(['error'=>1,'msg'=>'您登录错误次数超过10次，今日不可以再登录了！']));

if(IS_POST)
{
    $username = NoBadStr($_POST['username']);
    $password = trim($_POST['password']);
    
    strlen($username) < 2 && exit(json_encode(['error'=>1,'msg'=>'请输入正确的帐号']));
    strlen($password) < 6 && exit(json_encode(['error'=>1,'msg'=>'请输入正确的密码']));
    
    $user = $db->getrow('SELECT * FROM '.Table('user').' WHERE username = \''.$username.'\'');
    if(!$user)
    {
        $_SESSION['agent_login_fail']++;
        exit(json_encode(['error'=>1,'msg'=>'请输入正确的帐号']));
    }
	
	$user['gid'] != 2 && exit(json_encode(['error'=>1,'msg'=>'你不是代理，不可以登录']));
    
    //  登录日志信息
    $tmp = array();
    $tmp['username']   =   $username;
    $tmp['ip']          =   $_Y['ip'];
    $tmp['dateline']    =   TIMESTAMP;
    $tmp['status']      =   0;
    $logid = $db->add('agent_user_login',$tmp);
    
    ($user['password'] != Password($password)) && exit(json_encode(['error'=>1,'msg'=>'帐号或密码不正确']));
    
    //  登录日志信息
    $db->exec('UPDATE '.Table('agent_user_login').' SET status = 1 WHERE id = '.$logid);
    
    !$user['status'] && exit(json_encode(['error'=>1,'msg'=>'帐号被锁定']));
    
    unset($_SESSION['agent_login_fail']);
    
    //  存session
    $_SESSION['agent'] = $user;
	$_SESSION['agent']['dateline'] = TIMESTAMP;
	
	$db->exec('UPDATE '.Table('user').' SET last_time = '.TIMESTAMP.',last_ip = \''.$_Y['ip'].'\' WHERE id = '.$user['id']);
    
    exit(json_encode(['error'=>0,'msg'=>'登录成功']));
}

if($a == 'logout')  //  退出登录
{
    unset($_SESSION['agent']);
    
    ShowMsg('退出登录成功',U('index'));
}

$_uid && ShowMsg('你已经登录了',U('index'));

$tpl->display('index/login');

?>